# -*- coding:utf-8 -*-

import logging
import sys
import logging.handlers
import os
import threading
import json

from tornado import gen
from tornado_mysql import pools

_filehandlers = {}


def init_log(filename, level=logging.INFO, logger=None):
    # if filename is a *FILE*, log will write to file
    # otherwise we assume that filename is a stream(stdout, stderr, etc.)
    if isinstance(filename, str):
        filedir = os.path.dirname(filename)
        if not os.path.exists(filedir):
            os.makedirs(filedir)
        hdlr = logging.FileHandler(filename, 'a')
    else:
        stream = filename or sys.stderr
        hdlr = logging.StreamHandler(stream)

    format = "[%(asctime)s] [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s"
    datefmt = "%Y-%m-%d %H:%M:%S"
    fmt = logging.Formatter(fmt=format, datefmt=datefmt)
    hdlr.setFormatter(fmt)

    if logger is None:
        logger = logging.root

    logger.addHandler(hdlr)
    logger.setLevel(level)


def get_logger(name=None):
    return logging.getLogger(name)


class PoolManager(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        self.conf = read_conf_file("./conf.py")
        self.pool = pools.Pool(
            dict(host=self.conf["mysql_url"], port=self.conf["mysql_port"], user=self.conf["mysql_user"],
                 passwd=self.conf["mysql_passwd"], db=self.conf["db"]),
            max_idle_connections=1,
            max_recycle_sec=3)

    @staticmethod
    def instance():
        if not hasattr(PoolManager, "_instance"):
            with PoolManager._instance_lock:
                if not hasattr(PoolManager, "_instance"):
                    # New instance after double check
                    PoolManager._instance = PoolManager()
        return PoolManager._instance


def read_conf_file(file_path):
    try:
        with open(file_path) as f:
            conf_content = f.read()
            conf = {}
            # 执行配置，将配置项设置在 conf 中
            exec conf_content in conf
    except Exception, e:
        print >> sys.stderr, e
        os._exit(1)
    # encode conf_content
    return conf


class Result(object):
    def __init__(self, code=1, obj_dict=None, other_dict=None):
        self.code = code
        self.data = obj_dict
        if other_dict:
            self.other = other_dict


def parse_result(code=1, obj=None, other=None):
    obj_dict = None
    other_dict = None
    if obj:
        obj_dict = obj.__dict__
    if other:
        other_dict = other.__dict__
    result = Result(code, obj_dict, other_dict)
    return result

def parse_json(obj):
    return json.dumps(obj.__dict__)
